import 'dart:convert';

import 'package:easy_chat_app/commons/GlobalStatus.dart';
import 'package:easy_chat_app/commons/db/repository/LocalConversationRepository.dart';
import 'package:easy_chat_app/commons/db/service/LocalConversationService.dart';
import 'package:easy_chat_app/commons/model/AppUserDetail.dart';
import 'package:easy_chat_app/commons/model/GetUserPublicInfoByCodeResultData.dart';
import 'package:easy_chat_app/commons/utils/HttpUtils.dart';
import 'package:easy_chat_app/commons/utils/RouteUtils.dart';
import 'package:easy_chat_app/commons/utils/StringUtils.dart';
import 'package:easy_chat_app/mobile/page/MobileChatPage.dart';
import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:provider/provider.dart';

class MobileQRCodeScanPageChangeNotifier extends ChangeNotifier {
  String? qrCodeDataStr;

  void setQRCodeDataStr(String? newQRCodeData) {
    qrCodeDataStr = newQRCodeData;
    notifyListeners();
  }
}

class MobileQRCodeScanPage extends StatelessWidget {
  final Logger logger = Logger();

  MobileQRCodeScanPage({super.key});

  Widget _buildBarcode(AppUserDetail appUserDetail,
      MobileQRCodeScanPageChangeNotifier mobileQRCodeScanPageChangeNotifier) {
    String? ecCode;
    String displayText = "";
    String? qrCodeDataStr = mobileQRCodeScanPageChangeNotifier.qrCodeDataStr;
    if (StringUtils.isNotEmpty(qrCodeDataStr)) {
      logger.i("qrCodeData:qrCodeData");
      try {
        dynamic qrCodeData = jsonDecode(qrCodeDataStr!);
        if (qrCodeData is Map<String, dynamic>) {
          ecCode = qrCodeData["ECCode"];
        }
        if (StringUtils.isNotEmpty(ecCode)) {
          logger.i("ecCode: $ecCode");
          HttpUtils.getUserPublicInfoByCode(ecCode!).then((result) async {
            logger.i("getUserPublicInfoByCode.result: $result");
            GetUserPublicInfoByCodeResultData resultData = result.data!;
            bool isContact =
                (await HttpUtils.checkIsContact(resultData.id!)).data ?? false;
            if (isContact) {
              LocalConversation localConversation =
                  await LocalConversationService.syncConversation2Local(
                      LocalConversationTypeConstants.general,
                      resultData.id,
                      null);
              await RouteUtils.route2MobileChatPage(MobileChatPageParams(
                  contactUserId: resultData.id,
                  contactUserCode: resultData.code,
                  contactUserNickname: resultData.nickname!,
                  contactUserHeadPortrait: resultData.headPortrait,
                  contactUserHeadPortraitStoreType:
                      resultData.headPortraitStoreType,
                  currentUserId: appUserDetail.id!,
                  currentUserCode: appUserDetail.code,
                  currentUserNickName: appUserDetail.nickname,
                  currentUserHeadPortrait: appUserDetail.headPortrait,
                  currentUserHeadPortraitStoreType:
                      appUserDetail.headPortraitStoreType,
                  localConversation: localConversation));
            } else {
              await RouteUtils.route2MobileUserPublicInfoPage(
                  userPublicInfo: resultData);
              mobileQRCodeScanPageChangeNotifier.setQRCodeDataStr(null);
            }
          });
        }
      } on FormatException catch (ex) {
        ecCode = null;
        displayText = "二维码解析失败";
        logger.e(ex);
      }
    }
    return Text(
      displayText,
      overflow: TextOverflow.fade,
      style: const TextStyle(color: Colors.white),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<AppUserDetailChangeNotifier>(
        builder: (context, appUserDetailChangeNotifier, child) {
      AppUserDetail appUserDetail =
          appUserDetailChangeNotifier.getAppUserDetail();
      return MultiProvider(
        providers: [
          ChangeNotifierProvider(create: (context) {
            return MobileQRCodeScanPageChangeNotifier();
          })
        ],
        builder: (context, child) {
          MobileQRCodeScanPageChangeNotifier
              mobileQRCodeScanPageChangeNotifier =
              context.watch<MobileQRCodeScanPageChangeNotifier>();
          return Scaffold(
            appBar: AppBar(
              backgroundColor: Colors.black,
              leading: IconButton(
                  onPressed: () {
                    RouteUtils.pop();
                  },
                  icon: const Icon(
                    Icons.arrow_back,
                    color: Colors.white,
                  )),
            ),
            backgroundColor: Colors.black,
            body: Stack(
              children: [
                MobileScanner(
                  onDetect: (BarcodeCapture barcodes) {
                    String? newQRCodeData =
                        barcodes.barcodes.firstOrNull?.displayValue;
                    String? oldQRCodeData =
                        mobileQRCodeScanPageChangeNotifier.qrCodeDataStr;
                    logger.i(
                        "newQRCodeData:$newQRCodeData, oldQRCodeData: $oldQRCodeData");
                    if (oldQRCodeData == newQRCodeData) {
                      return;
                    }
                    mobileQRCodeScanPageChangeNotifier
                        .setQRCodeDataStr(newQRCodeData);
                  },
                ),
                Align(
                  alignment: Alignment.bottomCenter,
                  child: Container(
                    alignment: Alignment.bottomCenter,
                    height: 100,
                    color: Colors.black.withOpacity(0.4),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Expanded(
                            child: Center(
                                child: _buildBarcode(appUserDetail,
                                    mobileQRCodeScanPageChangeNotifier))),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          );
        },
      );
    });
  }
}
